#ifndef BSPLINES_H
#define BSPLINES_H

#include "Spline.h"
#include "B_Basis_function.h"
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
class any_BSplines
{
public:
    std::vector<double> a; // 给定的系数矩阵 
    int degree;            // 样条的阶数
    std::vector<double> x; // 节点向量

    any_BSplines(std::vector<double> a, int degree, std::vector<double> x)
    {
        this->a = a;
        this->degree = degree;
        this->x = x;
    }

    double any_BSplines_value(int degree, std::vector<double> knots, std::vector<double> coefficients, double x_value)
    {
        double result = 0.0;

        int n = knots.size(); // 节点数量
        for (int i = 0; i < n - degree - 1; i++) // 修正 i 从 0 开始，并确保范围正确
        {
            B_Basis_function B(degree, i, knots);
            result += coefficients[i] * B.value(x_value); // 计算样条值
        }
        return result;
    }
    void generate_and_plot_spline(const std::string& data_filename, const std::string& plot_script_filename, double x_min, double x_max, int num_points)
    {
        // 生成数据文件
        std::ofstream data_file(data_filename);
        if (!data_file.is_open())
        {
            std::cerr << "无法打开数据文件: " << data_filename << std::endl;
            return;
        }

        double step = (x_max - x_min) / num_points;
        for (int i = 0; i <= num_points; i++)
        {
            double x_value = x_min + i * step;
            double y_value = any_BSplines_value(degree, x, a, x_value);
            data_file << x_value << " " << y_value << std::endl;
        }
        data_file.close();

        // 创建 gnuplot 脚本文件
        std::ofstream plot_script_file(plot_script_filename);
        if (!plot_script_file.is_open())
        {
            std::cerr << "无法打开 gnuplot 脚本文件: " << plot_script_filename << std::endl;
            return;
        }

        plot_script_file << "# 设置输出文件为 PNG 格式\n";
        plot_script_file << "set terminal png size 800,600\n";
        plot_script_file << "# 设置输出文件的名称\n";
        plot_script_file << "set output 'spline_curve.png'\n";
        plot_script_file << "# 设置标题和轴标签\n";
        plot_script_file << "set title 'BSpline Curve'\n";
        plot_script_file << "set xlabel 'X Axis'\n";
        plot_script_file << "set ylabel 'Y Axis'\n";
        plot_script_file << "# 绘制数据文件中的曲线\n";
        plot_script_file << "plot '" << data_filename << "' with lines title 'BSpline'\n";
        plot_script_file.close();

        // 运行 gnuplot 脚本
        std::string command = "gnuplot " + plot_script_filename;
        int result = system(command.c_str());
        if (result != 0)
        {
            std::cerr << "gnuplot 执行失败" << std::endl;
        }
        else
        {
            std::cout << "曲线绘制完成，图像保存为 spline_curve.png" << std::endl;
        }
    }
};
#endif
